package com.simemg.reader.slice;

import com.simemg.reader.ResourceTable;
import com.simemg.reader.provider.PageListProvider;
import com.simemg.reader.store.Book;
import com.simemg.reader.store.Page;
import com.simemg.reader.utils.RouterUtil;
import com.simemg.reader.utils.StoreUtil;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.ListContainer;
import ohos.agp.components.RadioContainer;
import ohos.agp.components.Text;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class IndexSlice extends AbilitySlice {
    private Book book;
    private final List<Page> pageList = new ArrayList<>();
    private ListContainer pageListContainer;
    private PageListProvider pageListProvider;
    private RadioContainer sortContainer;
    private Text count;
    private boolean isDec = false;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_slice_index);

        initComponent();
        loadData(intent);
        addComponentListen();
    }

    void loadData(Intent intent) {
        int bookID = (Integer) RouterUtil.getData(intent);
        book = StoreUtil.searchBook(bookID);
        loadPageList();
    }

    void initComponent(){
        pageListContainer = (ListContainer)findComponentById(ResourceTable.Id_page_list);
        pageListProvider = new PageListProvider(pageList, this);
        pageListContainer.setItemProvider(pageListProvider);

        sortContainer = (RadioContainer) findComponentById(ResourceTable.Id_sort);
        count = (Text) findComponentById(ResourceTable.Id_count);

    }

    void loadPageList() {
        pageList.clear();
        List<Page> list = StoreUtil.searchPageList(book);
        pageList.addAll(list);
        pageListProvider.notifyDataChanged();
        pageListProvider.setNum(book.getNowNum());
        pageListContainer.scrollToCenter(Math.max(book.getNowNum() - 8, 0));

        count.setText("总共"+ pageList.size());
    }

    void addComponentListen() {
        pageListContainer.setItemClickedListener((listContainer, component, i, l) -> {
            Page page = pageList.get(i);
            StoreUtil.readPage(book, page.getNum());
            onBackPressed();
        });

        sortContainer.setMarkChangedListener((radioContainer, i) -> {
            if (i == 0 && isDec) {
                Collections.reverse(pageList);
                pageListProvider.notifyDataChanged();
                isDec = false;
            }
            if(i == 1 && !isDec) {
                Collections.reverse(pageList);
                pageListProvider.notifyDataChanged();
                isDec = true;
            }
        });
    }
}
